package com.brush.web.controller.sysrole;


import com.brush.common.annotation.Log;
import com.brush.common.constant.Constants;
import com.brush.common.core.controller.BaseController;
import com.brush.common.core.domain.AjaxResult;
import com.brush.common.core.domain.R;
import com.brush.common.core.domain.entity.SysRole;
import com.brush.common.core.domain.resp.AdminUserDetails;
import com.brush.common.enums.BusinessType;
import com.brush.framework.web.service.AdminTokenService;
import com.brush.framework.web.service.SysPermissionService;
import com.brush.system.domain.req.sysrole.SysRoleQueryReq;
import com.brush.system.domain.resp.sysrole.SysRoleResp;
import com.brush.system.service.SysMenuService;
import com.brush.system.service.SysRoleService;
import com.brush.system.service.SysUserService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

import java.util.Objects;

import static com.brush.common.utils.SecurityUtils.getLoginUser;
import static com.brush.common.utils.SecurityUtils.getUsername;

/**
 * ClassName: SysRoleController
 * Package: com.brush.web.controller.sysrole
 * Description:
 *
 * @Author luo
 * @Create 2024/8/25 15:59
 * @Version 1.0
 */
@Api(tags = "后台-角色api")
@RestController
@RequestMapping(value = "/admin/role")
public class SysRoleController extends BaseController {

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysPermissionService sysPermissionService;

    @Autowired
    private AdminTokenService adminTokenService;

    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @ApiOperation(value = "分页查询")
    @GetMapping(value = "/list")
    public R<PageInfo<SysRoleResp>> list(SysRoleQueryReq req) {
        PageInfo<SysRoleResp> page = this.sysRoleService.paginationQuery(req);
        return R.ok(page);
    }


    @ApiOperation(value = "根据角色ID查询")
    @GetMapping("/{id}")
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    public R<SysRoleResp> findById(@PathVariable(value = "id") Long id) {
        SysRoleResp resp = this.sysRoleService.findById(id);
        return R.ok(resp);
    }


    /**
     * 新增角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:add')")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@Validated @RequestBody SysRole role) {
        if (!this.sysRoleService.checkRoleNameUnique(role))
        {
            return R.fail("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (!this.sysRoleService.checkRoleKeyUnique(role))
        {
            return R.fail("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setCreateBy(getUsername());
        return super.isSuccess(this.sysRoleService.insertRole(role));

    }

    /**
     * 修改保存角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@Validated @RequestBody SysRole role)
    {
        this.sysRoleService.checkRoleAllowed(role);
        this.sysRoleService.checkRoleDataScope(role.getRoleId());
        if (!this.sysRoleService.checkRoleNameUnique(role))
        {
            return R.fail("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (!this.sysRoleService.checkRoleKeyUnique(role))
        {
            return R.fail("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateBy(getUsername());

        if (this.sysRoleService.updateRole(role) > 0)
        {
            // 更新缓存用户权限
            AdminUserDetails loginUser = getLoginUser();
            if (Objects.nonNull(loginUser.getUser()) && !loginUser.getPermissions().contains(Constants.ALL_PERMISSION))
            {
                loginUser.setPermissions(this.sysPermissionService.getMenuPermission(loginUser.getUser()));
                loginUser.setUser(this.sysUserService.selectUserByUserName(loginUser.getUser().getUserName()));
                this.adminTokenService.setLoginUser(loginUser);
            }
            return R.ok();
        }
        return R.fail("修改角色'" + role.getRoleName() + "'失败，请联系管理员");
    }

    /**
     * 修改保存数据权限
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public R dataScope(@RequestBody SysRole role)
    {
        this.sysRoleService.checkRoleAllowed(role);
        this.sysRoleService.checkRoleDataScope(role.getRoleId());
        return super.isSuccess(this.sysRoleService.authDataScope(role));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public R changeStatus(@RequestBody SysRole role)
    {
        this.sysRoleService.checkRoleAllowed(role);
        this.sysRoleService.checkRoleDataScope(role.getRoleId());
        role.setUpdateBy(getUsername());
        return super.isSuccess(this.sysRoleService.updateRoleStatus(role));
    }

    /**
     * 删除角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:remove')")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleIds}")
    public R remove(@PathVariable Long[] roleIds)
    {
        return super.isSuccess(this.sysRoleService.deleteRoleByIds(roleIds));
    }


}
